package com.ahdy.controller;

import com.ahdy.tool.Code;
import com.ahdy.tool.Result;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import static com.ahdy.tool.BigModelNew.domain;

@RestController
@RequestMapping("upload")
public class PictureUpload {

    /**
     *  获取配置文件中写好的的本地路径
     * */
    @Value("${uploadPathImg}")
    private String uploadPathImg;

    @PostMapping("")
    public Result upload(@RequestParam(value = "file") MultipartFile file) throws Exception {
        String file_src = "";
        System.out.println("file = " + file);
        System.out.println("file = " + file.getName());
        try {
            if (file != null) {
                String s = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.'));
                String fileName = System.currentTimeMillis() + UUID.randomUUID().toString().substring(3,8)+s;
                String upload_file_dir=uploadPathImg;//注意这里需要添加目录信息
                //4.第一次运行的时候，这个文件所在的目录往往是不存在的，这里需要创建一下目录（创建到了webapp下uploaded文件夹下）
                File upload_file_dir_file = new File(upload_file_dir);
                if (!upload_file_dir_file.exists())
                {
                    upload_file_dir_file.mkdirs();
                }
                //5.把浏览器上传的文件复制到希望的位置
                File targetFile = new File(upload_file_dir_file, fileName);
                file.transferTo(targetFile.getAbsoluteFile());
                file_src = targetFile.toString();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        domain(file_src);
        return new Result(Code.Res_ok,"ok","图片上传成功");
    }
}
